package com.xms.webresource.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xms.core.model.PagedList;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.webresource.entity.WebResource;
import com.xms.webresource.service.IWebResourceContentCoder;
import com.xms.webresource.service.IWebResourceFinderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author migo
 * @since 2021-08-29
 */
@RestController
@RequestMapping("{org}/api/webresource")
public class WebResourceFinderController extends ApiBaseController {
    private IWebResourceFinderService _webResourceFinderService;
    private IWebResourceContentCoder _webResourceContentCoder;
    @Autowired
    public WebResourceFinderController(IWebResourceFinderService webResourceFinderService,
                                       IWebResourceContentCoder webResourceContentCoder)
    {
        _webResourceFinderService = webResourceFinderService;
        _webResourceContentCoder = webResourceContentCoder;
    }

    @ApiOperation("查询web资源列表")
    @GetMapping("list")
    public JsonResultObject get(@RequestParam(value="webresourcetype", required = false) Integer type,
                                @RequestParam(value="name", required = false) String name,
                                @RequestParam(value="getall", required = false) Boolean getall,
                                @RequestParam(value="page", required = false) Integer page,
                                @RequestParam(value="pagesize", required = false) Integer pagesize,
                                @RequestParam(value="sortby", required = false) String sortby,
                                @RequestParam(value="sortdirection", required = false) String sortdirection)
    {
        LambdaQueryWrapper<WebResource> lambdaQueryWrapper = getSortedQueryWrapper(sortby, sortdirection);
        lambdaQueryWrapper.select(WebResource::getWebresourceid,WebResource::getName,
                WebResource::getWebresourcetype,WebResource::getCreatedby,WebResource::getCreatedon,WebResource::getDescription);
        if (StringUtil.notEmpty(name))
        {
            lambdaQueryWrapper.like(WebResource::getName, name);
        }
        if (type != null && type > 0)
        {
            lambdaQueryWrapper.eq(WebResource::getWebresourcetype, type);
        }
        if (getall != null && getall) {
            return JOk(_webResourceFinderService.list(lambdaQueryWrapper));
        }
        else if(page == null || pagesize == null){
            return JNotSpecifiedParams("page","pagesize");
        }
        page = (page <= 0 ? 1 : page);
        pagesize = (pagesize <= 0 ? 10 : pagesize);
        IPage<WebResource> datas = _webResourceFinderService.page(new Page<>(page, pagesize), lambdaQueryWrapper);
        PagedList<WebResource> result = new PagedList<>(datas.getRecords(), page, pagesize, datas.getTotal(), datas.getPages());

        return JOk(result);
    }

    @ApiOperation("根据ID查询单个Web资源")
    @GetMapping("getbyid/{id}")
    public JsonResultObject getById(@PathVariable(value="id", required = true) UUID id) throws UnsupportedEncodingException {
        WebResource entity = _webResourceFinderService.getById(id);
        if(entity == null){
            return JNotFound();
        }
        entity.setContent(_webResourceContentCoder.decode(entity.getContent()));
        return JOk(entity);
    }

    @ApiOperation("根据ID查询多个Web资源")
    @GetMapping("getbyids/{ids}")
    public JsonResultObject getById(@PathVariable(value="ids", required = true) String ids,
                                    @RequestParam(value="getbody", required = false) Boolean getbody) throws UnsupportedEncodingException {
        if(StringUtil.isEmpty(ids)){
            return JNotSpecifiedParams("ids");
        }
        List idList = Arrays.stream(StringUtil.splitSafe(ids, ",")).map(x->UUIDUtil.get(x)).collect(Collectors.toList());
        List<WebResource> result = _webResourceFinderService.getByIds(idList);
        if(getbody == null || !getbody){
            result.forEach(x->{x.setContent(null);});
        }
        return JOk(result);
    }

    @ApiOperation("加载Web资源内容")
    @RequestMapping(value = "getcontent/{ids}", produces="text/plain; charset=utf-8")
    public String getContent(@PathVariable(value="ids", required = true) String ids) throws UnsupportedEncodingException {
        if (StringUtil.notEmpty(ids))
        {
            List<UUID> idList = new ArrayList<>();
            if (ids.indexOf(",") > 0)
            {
                for (String item : ids.split(","))
                {
                    UUID id = UUIDUtil.get(item);
                    if (id != null)
                    {
                        idList.add(id);
                    }
                }
            }
            else
            {
                UUID id = UUIDUtil.get(ids);
                if (id != null)
                {
                    idList.add(id);
                }
            }
            StringBuilder content = new StringBuilder();
            List<WebResource> result = _webResourceFinderService.getByIds(idList);
            for (WebResource item : result)
            {
                String tmp = _webResourceContentCoder.decode(item.getContent());
                content.append(tmp);
            }
            return content.toString();
        }
        return "";
    }
}
